package com.coder.algorithm.leetcode

/**
 * 48. 旋转图像
 * @description: https://leetcode-cn.com/problems/rotate-image/
 * @author yuhus
 * @date: 2022/3/14
 */
class l_0048 {
    /**
     * 旋转后
     * 1、
     * matrix[row][col] -> matrix[col][n-row-1]
     * 2、
     * row = col
     * col = n-row-1
     * matrix[col][n-row-1] -> matrix[n-row-1][n-col-1]
     * 3.
     * row = n-row-1
     * col = n-col-1
     * matrix[n-row-1][n-col-1] -> matrix[n-col-1][row]
     * 4.
     * row = n-col-1
     * col = row
     * matrix[n-col-1][row] -> matrix[row][col]
     */
    fun rotate(matrix: Array<IntArray>) {
        val n = matrix.size
        for (i in 0 until n / 2) {
            for (j in 0 until  (n + 1)/2) {
                val temp = matrix[i][j]
                // 4.
                matrix[i][j] = matrix[n-j-1][i]
                // 3.
                matrix[n-j-1][i] = matrix[n-i-1][n-j-1]
                // 2.
                matrix[n-i-1][n-j-1] = matrix[j][n-i-1]
                // 1.
                matrix[j][n-i-1] = temp //matrix[i][j]
            }
        }
    }

    /**
     * 1、水平翻转
     *     matrix[row][col] = matrix[n-row-1][col]
     * 2、主对角线翻转
     *     matrix[row][col] = matrix[col][row]
     */
    fun ratate_solution2(matrix: Array<IntArray>) {
        val n = matrix.size
        // 水平翻转
        for (i in 0 until n/2) {
            for (j in 0 until n) {
                val temp = matrix[i][j]
                matrix[i][j] = matrix[n-i-1][j]
                matrix[n-i-1][j] = temp
            }
        }
        // 主对角线
        for (i in 0 until n) {
            for (j in 0 until i) {
                val temp = matrix[i][j]
                matrix[i][j] = matrix[j][i]
                matrix[j][i] = temp
            }
        }
    }
}